package com.youxin.chat.pay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youxin.common.constant.RedisKey;
import com.youxin.chat.pay.dto.PayRulesDto;
import com.youxin.chat.pay.mapper.PayRulesMapper;
import com.youxin.chat.pay.model.PayRules;
import com.youxin.chat.pay.service.PayRulesService;
import com.youxin.dozer.DozerUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * description: PayRulesServiceImpl <br>
 * date: 2020/2/29 11:44 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Service
public class PayRulesServiceImpl extends ServiceImpl<PayRulesMapper, PayRules> implements PayRulesService {

    @Resource
    private DozerUtils dozerUtils;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public PayRulesDto info() {
        String data = stringRedisTemplate.opsForValue().get(RedisKey.PAY_RULE_KEY);
        if (!StringUtils.isEmpty(data)) {
            PayRulesDto payRulesDto = JSONObject.parseObject(data,PayRulesDto.class);
            return payRulesDto;
        }
        List<PayRules> list = this.baseMapper.selectList(new LambdaQueryWrapper<>());
        Map<String, Object> map = new HashMap<>();
        for (PayRules item : list) {
            map.put(item.getRuleKey(), item.getRuleValue());
        }
        stringRedisTemplate.opsForValue().set(RedisKey.PAY_RULE_KEY, JSONObject.toJSONString(map),1, TimeUnit.DAYS);
        PayRulesDto payRulesDto = dozerUtils.map(map,PayRulesDto.class);
        return payRulesDto;
    }

    @Override
    public void saveRisk(PayRulesDto riskDto) {
        this.baseMapper.delete(new LambdaQueryWrapper<>());
        stringRedisTemplate.delete(RedisKey.PAY_RULE_KEY);
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(riskDto));
        Iterator iterator = jsonObject.keySet().iterator();
        List<PayRules> list = new ArrayList<>();
        while (iterator.hasNext()) {
            PayRules risk = new PayRules();
            String key = (String) iterator.next();
            risk.setRuleKey(key);
            risk.setRuleValue(jsonObject.getString(key));
            risk.setCreateTime(LocalDateTime.now());
            risk.setUpdateTime(LocalDateTime.now());
            list.add(risk);
        }
        saveBatch(list);
        stringRedisTemplate.opsForValue().set(RedisKey.PAY_RULE_KEY, jsonObject.toJSONString(),1, TimeUnit.DAYS);
    }
}
